package com.dreamlike.demo.HttpUtil.Core.ReuqestBodyHandler;

import com.dreamlike.demo.HttpUtil.Core.HttpDefinition;

import java.util.Arrays;
import java.util.stream.Collectors;

public class UrlencodedRequestBodyHandler implements StringRequestBodyHandler {
    private static final String FORMATION = "%s=%s";

    @Override
    public String trans(HttpDefinition httpDefinition, Object[] args) {

        if (httpDefinition.getRequestBodyIndex() == HttpDefinition.DEFAULT_REQUEST_BODY_INDEX) {
            Object bodyArg = args[(httpDefinition.getRequestBodyIndex())];
            return Arrays.stream(bodyArg.getClass().getDeclaredFields())
                    .peek(f -> f.setAccessible(true))
                    .map(f -> {
                        try {
                            return String.format(FORMATION, f.getName(),f.get(bodyArg));
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                        return null;
                    })
                    .collect(Collectors.joining("&"));

        }
        return httpDefinition.getParamRecord().entrySet()
                .stream()
                .map(e -> String.format(FORMATION, e.getValue(), args[e.getKey()].toString()))
                .collect(Collectors.joining("&"));
    }
}
